<template>
    <view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <!-- <view class="cellBox flex_wrap row_between">
            <u--text text="视频类型" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="chooseType()">
                <view class="title">{{ typeName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-picker
            :show="typeShow"
            ref="uPicker"
            :columns="columns"
            keyName="typeName"
            @confirm="confirm"
            @cancel="typeShow = false"
        ></u-picker> -->

        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="商品名称" color="#000" size="28rpx" />
            <view class="flex_wrap" @click="addName()">
                <view class="title">{{ videoName }}</view>
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-line color="#f3f3f3" length="2rpx"></u-line>
        <view class="cellBox flex_wrap row_between">
            <u--text text="商品售价（元）" color="#000" size="28rpx" />
            <view class="flex_wrap">
                <u--input
                    placeholder="请输入售价"
                    border="none"
                    v-model="price"
                    type="digit"
                    inputAlign="right"
                ></u--input>
            </view>
        </view>
        <view class="cellBox flex_wrap row_between">
            <u--text text="库存" color="#000" size="28rpx" />
            <view class="flex_wrap">
                <u--input
                    placeholder="请输入库存"
                    border="none"
                    v-model="quantity"
                    type="number"
                    inputAlign="right"
                ></u--input>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox">
            <u--text
                text="商品主图"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
            <view class="flex_wrap" style="flex-wrap: wrap">
                <view
                    class="uplondImg"
                    v-for="(item, index) in mainImgList"
                    :key="index"
                >
                    <image class="uplondImg_img" :src="item" mode=""></image>
                    <view class="uplondImg_icon" @click="delMain(index)">
                        <u-icon
                            name="close-circle-fill"
                            color="#737374"
                            size="20"
                        ></u-icon>
                    </view>
                </view>
                <view
                    class="uplondBtn"
                    @click="tapUpdateImg"
                    v-if="this.mainImgList.length < 6"
                >
                    <u-icon
                        name="camera-fill"
                        color="#D3D4D6"
                        size="28"
                    ></u-icon>
                </view>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between" @click="descriptionFun()">
            <u--text text="文字介绍" color="#000" size="28rpx" />
            <view class="title">{{ description }}</view>
            <view class="flex_wrap">
                <u-icon
                    name="arrow-right"
                    color="#777777 "
                    size="36rpx"
                ></u-icon>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox">
            <u--text
                text="商品详情图"
                color="#000"
                size="28rpx"
                margin="0 0 24rpx 0"
            />
            <!-- <view>
                <u-upload
                    multiple
                    :maxCount="10"
                    :fileList="fileList"
                    @delete="deletePic"
                    @afterRead="afterRead"
                    width="196rpx"
                    height="196rpx"
                >
                </u-upload>
            </view> -->
            <view class="flex_wrap" style="flex-wrap: wrap">
                <view
                    class="uplondImg"
                    v-for="(item, index) in detailImgList"
                    :key="index"
                >
                    <image class="uplondImg_img" :src="item" mode=""></image>
                    <view class="uplondImg_icon" @click="delDetail(index)">
                        <u-icon
                            name="close-circle-fill"
                            color="#737374"
                            size="20"
                        ></u-icon>
                    </view>
                </view>
                <view
                    class="uplondBtn"
                    @click="tapUpdateDetailImg"
                    v-if="this.detailImgList.length < 10"
                >
                    <u-icon
                        name="camera-fill"
                        color="#D3D4D6"
                        size="28"
                    ></u-icon>
                </view>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="商品类型" color="#000" size="28rpx" />
            <view class="flex_wrap">
                <u-radio-group v-model="salesmanGoodsType" placement="row">
                    <u-radio label="商品" :name="0"></u-radio>
                    <view style="width: 20rpx"></view>
                    <u-radio label="课程" :name="1"></u-radio>
                </u-radio-group>
            </view>
        </view>
        <u-gap height="8" bgColor="#F5F5F5 "></u-gap>
        <view class="cellBox flex_wrap row_between">
            <u--text text="通过后立即上架" color="#000" size="28rpx" />
            <view class="flex_wrap">
                <u-switch
                    iconPlacement="right"
                    v-model="checkedOnline"
                    :activeValue="1"
                    :inactiveValue="0"
                ></u-switch>
            </view>
        </view>
        <view class="bottom">
            <u-button
                :loading="btnLoading"
                text="发布"
                color="#1682FF"
                shape="circle"
                @click="sumbit()"
            />
        </view>

        <u-modal
            :show="nameShow"
            showCancelButton
            title="商品名称"
            @confirm="nameConfirm"
            @cancel="nameShow = false"
        >
            <view style="width: 560rpx; margin: 0 auto">
                <u-textarea
                    ref="textareaName"
                    height="300rpx"
                    v-model="videoName1"
                    :customStyle="textAreaCustomStyle"
                    placeholder="请输入内容"
                    fixed
                    count
                    maxlength="100"
                ></u-textarea>
            </view>
        </u-modal>
        <cropper
            ref="cropper"
            selWidth="660rpx"
            selHeight="660rpx"
            @upload="myUpload"
            avatarStyle="width:100vw;height:100vw;"
        >
        </cropper>
        <cropper
            ref="cropperTwo"
            selWidth="660rpx"
            selHeight="660rpx"
            @upload="myUploadDetail"
            avatarStyle="width:100vw;height:100vw;"
        >
        </cropper>
    </view>
</template>

<script>
import { baseUrl } from "@/config/tendIdConfig";
import { mapGetters } from "vuex";
import {
    createCustomerGoods,
    getCustomerGoodsInfo,
    updateCustomerGoods,
} from "@/api/shop.js";
import { numDiv, numMulti } from "@/js_sdk/nl-precisionNum/precisionNum.js";
import { formatDecimal } from "@/utils/index.js";
import cropper from "@/components/cropper/cropper.vue";
export default {
    data() {
        return {
            formatDecimal: formatDecimal,
            btnLoading: false,
            textAreaCustomStyle: {
                backgroundColor: "#EDEDED",
                color: "#666",
                width: "100%",
                padding: "20rpx",
                paddingBottom: "40rpx",
                boxSizing: "border-box",
                fontSize: "26rpx",
            },
            typeShow: false,
            columns: [],
            typeName: "",
            typeNameId: "",
            nameShow: false,
            videoName: "",
            videoName1: "",
            videoInfo: "",
            videoInfo1: "",
            fileList: [],
            fileList1: [],
            quantity: "",
            price: "",
            salesmanGoodsType: 0,
            checkedOnline: 1,
            id: "",

            mainImg: "",
            mainImgList: [],
            description: "",
            detailImg: "",
            detailImgList: [],
        };
    },
    computed: {
        ...mapGetters(["userInfo"], cropper),
    },
    onReady() {
        this.$refs.textareaName.setFormatter(this.formatterName);
    },
    onShow() {
        let that = this;
        uni.$on("description", function (data) {
            that.description = data;
        });
    },
    onLoad(e) {
        this.id = e?.id ?? null;
        console.log("e :>> ", this.id);
        if (this.id) {
            getCustomerGoodsInfo(this.id).then(({ code, data }) => {
                console.log("res :----->> ", data?.topImage.split(","));
                console.log("res :---2222-->> ", data?.detailImage.split(","));
                if (code === 200) {
                    this.videoName = data?.goodsName;
                    this.description = data?.description ?? "";
                    this.quantity = data?.quantity;
                    this.price = data.price ? numDiv(data?.price, 100) : 0;
                    this.submitStatus = data?.submitStatus;
                    this.checkedOnline = data?.checkedOnline;
                    this.salesmanGoodsType = data?.salesmanGoodsType;
                    this.detailImgList = data?.detailImage.split(",");
                    this.mainImgList = data?.topImage.split(",");
                }
            });
        }
    },
    onUnload() {
        // 移除监听事件
        uni.$off("description");
    },
    methods: {
        descriptionFun() {
            uni.$u.route({
                url: "pages_shop1/salesmanGoods/createGoods/description",
                params: { description: this.description },
            });
        },
        delMain(index) {
            this.mainImgList.splice(index, 1);
        },
        tapUpdateImg() {
            this.$refs.cropper.fSelect();
        },
        //上传返回图片
        myUpload(rsp) {
            let _this = this;
            uni.uploadFile({
                url: `${baseUrl}/salesman/fileOss/uploadFileImg`, //这里写自己的接口
                filePath: rsp.path,
                header: {
                    "Content-Type": "multipart/form-data",
                    Authorization:
                        `Bearer ${uni.getStorageSync("access_token")}` || "",
                },
                name: "file",
                success: (res) => {
                    const result = JSON.parse(res.data);
                    if (result.code === 200) {
                        uni.showToast({
                            title: "上传成功",
                            icon: "success",
                        });
                        this.mainImg = result.data;
                        this.mainImgList.push(this.mainImg);
                        console.log(this.mainImg, ">>", this.mainImgList);
                    } else {
                        uni.showToast({
                            title: "上传失败",
                            icon: "fail",
                        });
                    }
                },
            });
        },
        delDetail(index) {
            this.detailImgList.splice(index, 1);
        },
        tapUpdateDetailImg() {
            this.$refs.cropperTwo.fSelect();
        },
        //上传详情返回图片
        myUploadDetail(rsp) {
            let _this = this;
            uni.uploadFile({
                url: `${baseUrl}/salesman/fileOss/uploadFileImg`, //这里写自己的接口
                filePath: rsp.path,
                header: {
                    "Content-Type": "multipart/form-data",
                    Authorization:
                        `Bearer ${uni.getStorageSync("access_token")}` || "",
                },
                name: "file",
                success: (res) => {
                    const result = JSON.parse(res.data);
                    if (result.code === 200) {
                        uni.showToast({
                            title: "上传成功",
                            icon: "success",
                        });
                        this.detailImg = result.data;
                        this.detailImgList.push(this.detailImg);
                        console.log(this.detailImg, ">>", this.detailImgList);
                    } else {
                        uni.showToast({
                            title: "上传失败",
                            icon: "fail",
                        });
                    }
                },
            });
        },

        formatterName(value) {
            if (value.length > 100) {
                return value.slice(0, 100);
            } else {
                return value;
            }
        },
        sumbit() {
            if (!this.videoName.length) return uni.$u.toast("请输入商品名字！");
            if (!this.price) return uni.$u.toast("请输入商品价格！");
            if (!this.quantity) return uni.$u.toast("请输入库存数量！");

            if (!this.detailImgList.length)
                return uni.$u.toast("请上传详情图片！");
            if (!this.mainImgList.length)
                return uni.$u.toast("请上传主图图片！");

            this.btnLoading = true;
            console.log(this.mainImgList, this.detailImgList);
            const topImage = this.mainImgList.map((v) => v);
            const detailImage = this.detailImgList.map((v) => v);
            const params = {
                submitStatus: 1,
                checkedOnline: this.checkedOnline,
                salesmanGoodsType: this.salesmanGoodsType,
                topImage: topImage.toString(),
                price: numMulti(this.price, 100),
                detailImage: detailImage.toString(),
                thumbnail: topImage[0],
                goodsName: this.videoName,
                quantity: this.quantity,
                description: this.description,
            };
            console.log(params, "参数");
            if (this.id) {
                updateCustomerGoods({ ...params, goodsId: this.id })
                    .then((res) => {
                        if (res.code === 200) {
                            uni.$u.toast("提交成功");
                            // uni.$emit("currentTab", 2);
                            uni.navigateBack({
                                delta: 1,
                            });
                        }
                    })
                    .finally(() => {
                        this.btnLoading = false;
                    });
                return;
            }
            createCustomerGoods(params)
                .then((res) => {
                    if (res.code === 200) {
                        uni.$u.toast("提交成功");
                        // uni.$emit("currentTab", 2);
                        uni.navigateBack({
                            delta: 1,
                        });
                    }
                })
                .finally(() => {
                    this.btnLoading = false;
                });
        },

        addName() {
            this.videoName1 = this.videoName;
            this.nameShow = true;
        },
        nameConfirm() {
            this.nameShow = false;
            this.videoName = this.videoName1;
        },
        chooseType() {
            this.typeShow = true;
        },
        // 确认选中的数据
        confirm(e) {
            this.typeName = e.value[0].typeName;
            this.typeNameId = e.value[0].id;
            console.log(this.typeNameId, "mmmm", this.typeName);
            this.typeShow = false;
        },
    },
};
</script>
<style lang="scss" scoped>
page {
    background: #f5f5f5;
    color: #333333;
}

.cellBox {
    background-color: #ffffff;
    padding: 34rpx 28rpx;
    /* line-height: 112rpx; */
    font-size: 32rpx;
    color: #3d3d3d;
}

.title {
    overflow: hidden;
    width: 500rpx;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: end;
}
.bottom {
    width: 100%;
    padding: 40rpx 60rpx;
    box-sizing: border-box;
}
.uplondBtn {
    width: 198rpx;
    height: 198rpx;
    background-color: #f4f5f7;
    display: flex;
    justify-content: center;
    align-items: center;
}
.uplondImg {
    width: 198rpx;
    height: 198rpx;
    background-color: #f4f5f7;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    &_img {
        width: 198rpx;
        height: 198rpx;
    }
    &_icon {
        position: absolute;
        top: 0;
        right: 0;
    }
}
</style>
